from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from app04.models import Goods, User, Favourable, Leave
from app04.serializer import *
from django.views import View
from django.http import JsonResponse
# Create your views here.
class UserView(View):
    def get(self,request):
        # 查找所有的用户
        user_list = User.objects.all()
        user_data = []
        for i in user_list:
            user_data.append({'id':i.pk,'user_name':i.user_name,'leave':{'id':i.leave.pk,'name':i.leave.name}})
        return JsonResponse({'data':user_data,'msg':'OK','code':200})
    def post(self,request):
        user_id = request.POST.get('user_id')
        leave_id = 2
        user_obj = User.objects.filter(pk=user_id)
        user_obj.update(leave_id=leave_id)
        favourable_list = [i for i in Favourable.objects.all()]
        user_obj.first().favourable.add(*favourable_list)
        # user_obj.save()
        return JsonResponse({'msg':'升级成功','code':200})


class GoodsView(APIView):
    def get(self, request):
        # 查询所有的商品
        goods_list = Goods.objects.all()
        goods_data = GoodsSER(goods_list,many=True)
        data = goods_data.data
        return Response(data)
        # print(goods_list)
        # goods_data = [{'id': i.pk, 'name': i.name, 'price': i.price, 'counter': i.counter} for i in goods_list]
        # return JsonResponse({'data': goods_data, 'msg': 'OK', 'code': 200})


class LoginView(View):
    def post(self,request):
        username = request.POST.get('user_name')
        password = request.POST.get('password')

        # 去数据库查找用户，用来判断用户是否存在
        user_obj = User.objects.filter(user_name=username).first()
        # 判断用户是否存在
        if user_obj:
            if password == user_obj.password:
                return JsonResponse({'msg':'登录成功','code':200,'username':username,'user_id':user_obj.pk})
            else:
                return JsonResponse({'msg':'用户名或密码不正确','code':400})
        else:
            return JsonResponse({'msg':'用户不存在','code':400})